package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.AddressDao;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.OderInformation;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private AddressDao addressDao;
    //体检预约
    public Result order(Map map) throws Exception {
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//预约日期
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null){//指定日期没有进行体检设置，没法体检预约,与之前的预约有区别
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number){//说明已经预约满了
            return new Result(false,MessageConstant.ORDER_FULL);
        }
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member != null){//说明已经是会员
            //判断是否在重复预约
            Integer memberId = member.getId();//会员id
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约的日期
            String setmealId = (String) map.get("setmealId");//套餐id
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //根据order条件来查询,这个地方牛逼！
            List<Order> list = orderDao.findByCondition(order);//通用方法
            if (list != null && list.size() >0){//说明用户重复预约
                return new Result(false,MessageConstant.HAS_ORDERED);
            }
        }else {
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            System.out.println(member);
            memberDao.add(member);//将会员信息自动注册
        }
        //5、预约成功，更新当日的已预约人数
        Order order = new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(DateUtils.parseString2Date(orderDate));
        order.setOrderType((String) map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
//        order.setSetmealId((Integer) map.get("setmealId"));
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));
        orderDao.add(order);//保存预约信息


        //设置订单关联地图
        Integer order_id = order.getId();
        if (order_id!=null&&order_id!=0) {
            Object object = map.get("aname");
            String str = object.toString();
            System.out.println("str:"+str+"order_id"+order_id);
            String s = str.substring(2, str.length() - 2);

            Integer address_id = addressDao.getIdByAddress(s);
            Map map1 = new HashMap();
            map1.put("order_id", order_id);
            map1.put("address_id", address_id);
            orderDao.setRelAddressAndOrder(map1);
        }
        //更新当日的已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());//页面只需要id
    }

    //体检预约
    @Override
    public Result orders(Map map) throws Exception {
        /**
         1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
         2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
         3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
         4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
         5、预约成功，更新当日的已预约人数
         */

        //获取日期
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);//根据日期查询预约设置信息
        if (orderSetting == null) {
            //所选日期没有提前进行预约设置，不能完成预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            //所选日期已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //判断是否在重复预约
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            Integer memberId = member.getId();//会员id
            Integer setmealId = Integer.parseInt((String) map.get("setmealId"));//套餐id
            Order order = new Order(memberId, date, setmealId);
            List<Order> orderList = orderDao.findByCondition(order);
            if (orderList != null && orderList.size() > 0) {
                //用户在重复预约，不能完成预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }

        if (member == null) {
            //当前用户不是会员，需要自动完成注册
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            String birthday = (String) map.get("birthday");
            Date day = DateUtils.parseString2Date(birthday);
            member.setBirthday(day);
            memberDao.add(member);
        }

        //保存预约信息
        Order order = new Order(member.getId(),
                date,
                (String) map.get("orderType"),
                Order.ORDERSTATUS_NO,
                Integer.parseInt((String) map.get("setmealId")));
        orderDao.add(order);

        //更新已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    //根据id查询预约详细信息（包括会员姓名、套餐名称、预约基本信息）
    public Map findById(Integer id) {
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            try {
                map.put("orderDate", DateUtils.parseDate2String(orderDate));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    @Override
    public List<Setmeal> findSetmeal() {
        return orderDao.findSetmeal();
    }
    //预约管理信息查询
    @Override
    public PageResult findAll(QueryPageBean queryPageBean) {
        //获取查询条件信息
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        String queryString = queryPageBean.getQueryString();
        //调用pagehelper查询信息
        PageHelper.startPage(currentPage,pageSize);
        Page<OderInformation> page =memberDao.findAllIformation(queryString);
        //返回结果s
        return new PageResult(page.getTotal(),page.getResult());
    }


    //更新预约状态根据ID
    @Override
    public void updateById(Integer id) {
         orderDao.updateById(id);
    }

    //删除预约
    @Override
    public void cancelById(Integer id) {
        orderDao.cancelById(id);
    }
}
